package com.yang.simple_rpc.server.register;

import com.alibaba.fastjson.JSON;
import com.yang.simple_rpc.common.serializer.SimpleSerializer;
import com.yang.simple_rpc.common.service.Service;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;

import static com.yang.simple_rpc.common.constant.SimpleConstant.*;

/**
 * zookeeper服务注册类，提供服务注册和服务暴露的能力
 * @author : morikawaaaa
 * @date : 2022
 */
public class ZookeeperExportServiceRegister extends DefaultServiceRegister implements ServiceRegister{
    private ZkClient zkClient;

    public ZookeeperExportServiceRegister(String zkAddress, Integer port, String protocol){
        zkClient = new ZkClient(zkAddress);
        zkClient.setZkSerializer(new SimpleSerializer());
        this.port = port;
        this.protocol = protocol;
    }

    //将服务节点添加信息并注册到zookeeper，然后暴露端口
    @Override
    public void register(ServiceObject so) throws Exception {
        super.register(so);
        Service service = new Service();
        String host = InetAddress.getLocalHost().getHostAddress();
        String address = host + ":" + port;
        service.setAddress(address);
        service.setName(so.getName());
        service.setProtocol(protocol);
        this.exportService(service);
    }


    /**
     * 暴露服务，在zk服务器上创建节点对应提供的服务,新服务覆盖旧服务
     * @param serviceResource 需要暴露的服务
     */
    public void exportService(Service serviceResource){
        String serviceName = serviceResource.getName();
        String uri = JSON.toJSONString(serviceResource);
        try{
            uri = URLEncoder.encode(uri, UTF_8);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        String servicePath = ZK_SERVICE_PATH + PATH_DELIMITER + serviceName + "/service";
        if(!zkClient.exists(servicePath)){
            zkClient.createPersistent(servicePath, true);
        }
        String uriPath = servicePath + PATH_DELIMITER + uri;

        if(zkClient.exists(uriPath)){
            zkClient.delete(uriPath);
        }
        zkClient.createEphemeral(uriPath);

    }
}
